package com.cuijq.virwallet.controller;

import com.cuijq.virwallet.exception.NoSufficientBalanceException;
import com.cuijq.virwallet.repository.entity.VirtualWalletEntity;
import com.cuijq.virwallet.service.VirtualWalletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;

@Controller
@RequestMapping("wallet")
public class VirWalletController {
    // 通过构造函数或者IOC框架注入
    @Autowired
    private VirtualWalletService virtualWalletService;

    public BigDecimal getBalance(Long walletId) {
       return virtualWalletService.getBalance(walletId);
    }//查询余额

    public void debit(Long walletId, BigDecimal amount) throws NoSufficientBalanceException {
         virtualWalletService.debit(walletId,amount);
    } //出账

    public void credit(Long walletId, BigDecimal amount) {
        virtualWalletService.credit(walletId,amount);
    }
    //入账
    public void transfer(Long fromWalletId, Long toWalletId, BigDecimal amount) {
        virtualWalletService.transfer(fromWalletId,toWalletId,amount);
    } //转账

    /**
     * 添加
     * @param virtualWalletEntity
     * @return
     */
    @RequestMapping(value="/add",method= RequestMethod.POST)
    public String add(VirtualWalletEntity virtualWalletEntity){
        virtualWalletService.save(virtualWalletEntity);
        return "forward:/wallet/list";
    }
    /**
     * 查询所有人的钱包
     * @return
     */
    @RequestMapping(value="/list")
    public ModelAndView list(){
        ModelAndView mav=new ModelAndView();
        mav.addObject("walletList", virtualWalletService.findAll());
        mav.setViewName("walletList");
        return mav;
    }

    /**
     * 修改
     * @param virtualWalletEntity
     * @return
     */
    @PostMapping(value="/update")
    public String update(VirtualWalletEntity virtualWalletEntity){
        virtualWalletService.save(virtualWalletEntity);
        return "forward:/wallet/list";
    }

    @GetMapping(value="/preUpdate/{id}")
    public ModelAndView preUpdate(@PathVariable("id") Long id){
        ModelAndView mav=new ModelAndView();
        VirtualWalletEntity virtualWalletEntity =new VirtualWalletEntity();
        Example<VirtualWalletEntity> example = Example.of(virtualWalletEntity);
        virtualWalletEntity.setId(id);
        VirtualWalletEntity wallet = virtualWalletService.findOne(example).orElse(new VirtualWalletEntity());
        mav.addObject("wallet",wallet );
        mav.setViewName("walletUpdate");
        return mav;
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value="/delete",method=RequestMethod.GET)
    public String delete(Long id){
        virtualWalletService.deleteById(id);
        return "forward:/wallet/list";
    }
}
